# from django.http import HttpResponse
# from rest_framework.permissions import IsAuthenticated
# from rest_framework.response import Response
# from rest_framework.views import APIView
#
# from apps.recruit.models import Enterprise, Recruit, City
# from apps.recruit.serializers.enterpriseerializer import RecruitSerializerSimple, CitySerializer, RecruitSerializer, \
#     EnterpriseSerializer
#
#
# # 获取推荐的招聘信息列表
# class SearchRecommendView(APIView):
#
#     def get(self, request):
#         queryset = Recruit.objects.all().order_by('-id')[:4]
#         serializer = RecruitSerializerSimple(instance=queryset, many=True)
#
#         return Response(serializer.data)
#
#
# # 获取最新的招聘信息列表
# class SearchLatestView(APIView):
#     def get(self, request):
#         queryset = Recruit.objects.all().order_by('-createtime')[:4]
#         serializer = RecruitSerializerSimple(instance=queryset, many=True)
#
#         return Response(serializer.data)
#
#
# # 获取热门企业列表
# class SearchHotlistView(APIView):
#
#     def get(self, request):
#         queryset = Enterprise.objects.all().order_by('-visits')[:4]
#         serializer = RecruitSerializerSimple(instance=queryset, many=True)
#
#         return Response(serializer.data)
#
#
# # 获取热门城市
# class CityHotlistView(APIView):
#     def get(self, request):
#         queryset = City.objects.filter(ishot=1)
#         serializer = CitySerializer(instance=queryset, many=True)
#
#         return Response(serializer.data)
#
#
# # 搜索某个职位
# class SearchCityKeywordView(APIView):
#     def post(self, request):
#         cityname = request.data.get('cityname')
#         keyword = request.data.get('keyword')
#         jobs = Recruit.objects.filter(state='1').order_by('-createtime')
#         jobs_list = []
#         # 判断是否传递参数cityname或keyword
#         if not cityname and not keyword:
#             jobs_list = jobs
#         elif cityname and not keyword:
#             for job in jobs:
#                 jobs_list.append(job)
#         elif not cityname and keyword:
#             for job in jobs:
#                 if job.jobname.lower().find(keyword.lower()) != -1:
#                     jobs_list.append(job)
#         else:
#             for job in jobs:
#                 if job.city == cityname and job.jobname.lower().find(keyword.lower()) != -1:
#                     jobs_list.append(job)
#
#         serializer = RecruitSerializer(jobs_list, many=True)
#         return Response(serializer.data)
#
#
# # 获取职位详情信息
# class RecruitIDView(APIView):
#     def get(self, request, pk):
#         queryset = Recruit.objects.get(id=pk)
#         serializer = RecruitSerializer(queryset)
#         return Response(serializer.data)
#
#
# # 增加某个职位的访问量
# class RecruitIDVisitView(APIView):
#     def put(self, request, pk):
#         queryset = Recruit.objects.get(id=pk)
#         queryset.visits += 1
#         queryset.save()
#         return Response({"message": "更新成功", "success": True})
#
#
# # 收藏职位
# class RecruitIDCollectView(APIView):
#     permission_classes = [IsAuthenticated]
#
#     def post(self, request, pk):
#         user = request.user
#         recruit = Recruit.objects.get(id=pk)
#         recruit.users.add(user)
#         recruit.save()
#         return Response({"message": "收藏成功", "success": True})
#
#
# # 取消收藏职位
# class RecruitIDCollectsView(APIView):
#     permission_classes = [IsAuthenticated]
#
#     def post(self, request, pk):
#         user = request.user
#         recruit = Recruit.objects.get(id=pk)
#         recruit.users.remove(user)
#         recruit.save()
#         return Response({"message": "取消收藏成功", "success": True})
#
#
# # 获取企业详情信息
# class EnterpriseIDView(APIView):
#     def get(self, request, pk):
#         queryset = Enterprise.objects.get(id=pk)
#         serializer = EnterpriseSerializer(queryset)
#         return Response(serializer.data)
#
#
# # 增加企业的访问量
# class EnterpriseIDVisitView(APIView):
#     def put(self, request, pk):
#         queryset = Recruit.objects.get(id=pk)
#         queryset.visits += 1
#         queryset.save()
#         return Response({"message": "更新成功", "success": True})
#
#
# # 收藏公司,后台会自行动态判断
# class EnterpriseIDCollect(APIView):
#     permission_classes = [IsAuthenticated]
#
#     def post(self, request, pk):
#         user = request.user
#         recruit = Enterprise.objects.get(id=pk)
#         recruit.users.add(user)
#         recruit.save()
#         return Response({"message": "收藏公司成功", "success": True})
#
#
# # 取消收藏公司,后台会自行动态判断
# class EnterpriseIDCollects(APIView):
#     permission_classes = [IsAuthenticated]
#
#     def post(self, request, pk):
#         user = request.user
#         recruit = Enterprise.objects.get(id=pk)
#         recruit.users.remove(user)
#         recruit.save()
#         return Response({"message": "取消收藏公司成功", "success": True})

import json

from django.conf import settings
from django.shortcuts import render

# Create your views here.
from rest_framework import mixins
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from .models import Recruit, Enterprise, City
from apps.recruit.serializers.enterpriseerializer import RecruitSerializer, EnterpriseSerializer, CitySerializer, RecruitInfoSerializer, \
    EnterpriseInfoSerializer


class RecommendView(APIView):
    """获取推荐的招聘列表信息"""

    def get(self, request):
        queryset = Recruit.objects.all()

        # 序列化招聘信息
        serializer = RecruitSerializer(queryset, many=True)

        return Response(serializer.data)


class LatestJobView(APIView):
    """获取最新的招聘信息列表"""

    def get(self, request):
        queryset = Recruit.objects.all().order_by('-createtime')
        # 序列化招聘信息
        serializer = RecruitSerializer(queryset, many=True)
        return Response(serializer.data)


class HotlistView(APIView):
    # 热门企业
    def get(self, request):
        queryset = Enterprise.objects.all().order_by('-visits')
        # 序列化热门企业
        serializer = EnterpriseSerializer(queryset, many=True)
        return Response(serializer.data)


class HotCityView(APIView):
    """热门城市"""

    def get(self, request):
        queryset = City.objects.filter(ishot=1)
        # 序列化热门企业
        serializer = CitySerializer(queryset, many=True)
        return Response(serializer.data)


class PositionView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    """职位相关"""
    lookup_value_regex = '\d+'
    queryset = Recruit.objects.all()
    serializer_class = RecruitInfoSerializer

    @action(methods=['put'], detail=True)
    def visit(self, request,pk):
        job = self.get_object()
        job.visits += 1
        job.save()
        return Response({"message": "更新成功", "success": True})

    @action(methods=['post'], detail=True)
    def collect(self, request, pk):
        permission_classes = [IsAuthenticated]
        user = request.user
        job = self.get_object()
        job.users.add(user)
        job.save()
        return Response({"message": "收藏成功", "success": True})


class EnterpriseView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    """公司相关"""
    lookup_value_regex = '\d+'
    queryset = Enterprise.objects.all()
    serializer_class = EnterpriseInfoSerializer

    # def retrieve(self, request, *args, **kwargs):
    #     myobj = self.get_object()
    #     res = myobj.logo.url
    #     print(res)
    #     print(myobj.logo.url)
    #     return Response('ok')


    @action(methods=['put'], detail=True)
    def visit(self, request,pk):
        company = self.get_object()
        company.visits += 1
        company.save()
        return Response({"message": "更新成功", "success": True})

    @action(methods=['post'], detail=True)
    def collect(self, request, pk):
        permission_classes = [IsAuthenticated]
        user = request.user
        company = self.get_object()
        company.users.add(user)
        company.save()
        return Response({"message": "收藏成功", "success": True})


class SerachJobView(APIView):
    def post(self, request):
        queryset = Recruit.objects.all()
        serializer = RecruitSerializer(queryset, many=True)

        json_str = request.body.decode()
        # 使用json模块将原始数据转成字典
        json_dict = json.loads(json_str)
        # 提取字典的参数
        name = json_dict.get('cityname')
        keyword = json_dict.get('keyword')

        if not name:
            keyword_data = queryset.filter(jobname__icontains=keyword.lower())

        if not keyword:
            keyword_data = queryset.filter(city=name)

        if name and keyword:
            name_dataes = queryset.filter(city=name)

            keyword_data = name_dataes.filter(jobname__icontains=keyword.lower())

        serializer = RecruitSerializer(keyword_data, many=True)
        return Response(serializer.data)

class CancelJobView(APIView):
    """取消职位收藏"""
    def post(self,request,pk):

        permission_classes = [IsAuthenticated]
        user = request.user
        job = Recruit.objects.get(id=pk)
        job.users.remove(user)
        job.save()
        return Response({"message": "取消收藏成功", "success": True})


class CancelEnterpriseView(APIView):
    """取消公司收藏"""

    def post(self, request, pk):
        permission_classes = [IsAuthenticated]
        user = request.user
        company = Enterprise.objects.get(id=pk)
        company.users.remove(user)
        company.save()
        return Response({"message": "取消收藏成功", "success": True})
